package com.ruoyi.project.modules.page.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.project.modules.category.domain.Category;
import com.ruoyi.project.modules.category.mapper.CategoryMapper;
import com.ruoyi.project.modules.fileInfo.domain.FileInf;
import com.ruoyi.project.modules.fileInfo.mapper.FileInfoMapper;
import com.ruoyi.project.modules.interfaceObject.domain.InterfaceObject;
import com.ruoyi.project.modules.interfaceObject.mapper.InterfaceObjectMapper;
import com.ruoyi.project.modules.interfaceinfo.domain.CategoryPageDto;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.mapper.InterfaceInfoMapper;
import com.ruoyi.project.modules.page.domain.Page;
import com.ruoyi.project.modules.page.domain.PageInterfaceDto;
import com.ruoyi.project.modules.page.mapper.PageMapper;
import com.ruoyi.project.modules.page.service.IPageService;
import com.ruoyi.project.modules.productVersionObejct.domain.ProductVersionObejct;
import com.ruoyi.project.modules.productVersionObejct.mapper.ProductVersionObejctMapper;
import com.ruoyi.project.modules.userDataAuth.domain.UserDataAuth;
import com.ruoyi.project.modules.userDataAuth.mapper.UserDataAuthMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 页面Service业务层处理
 *
 * @author smallrain
 * @date 2021-11-06
 */
@Service
public class PageServiceImpl implements IPageService {
    @Resource
    private PageMapper pageMapper;
    @Resource
    private FileInfoMapper fileInfoMapper;
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    /**
     * 查询页面
     *
     * @param id 页面主键
     * @return 页面
     */
    @Override
    public Page selectPageById(Long id) {
        return pageMapper.selectPageById(id);
    }

    /**
     * 查询页面列表
     *
     * @param page 页面
     * @return 页面
     */
    @Override
    public List<Page> selectPageList(Page page) {
        return pageMapper.selectPageList(page);
    }

    /**
     * 新增页面
     *
     * @param page 页面
     * @return 结果
     */
    @Override
    public int insertPage(Page page) {
        if (page.getParentId() != null) {
            Page page1 = this.selectPageById(page.getParentId());
            if (page1 == null) {
                page.setPageLevel("1");
            } else {
                page.setPageLevel((Integer.parseInt(page1.getPageLevel()) + 1) + "");
                page.setCategoryId(page1.getCategoryId());
            }

        }
        page.setCreateTime(DateUtils.getNowDate());
        page.setCreateBy(ShiroUtils.getLoginName());
        if (page.getCategoryId() != null) {
            Category category = this.categoryMapper.selectCategoryById(page.getCategoryId());
            page.setCategoryCode(category.getCode());
        }
        int i = pageMapper.insertPage(page);
        insertInterfaceObject(page.getId(), page.getInterfaceIds(), null);
        return i;
    }

    @Resource
    private ProductVersionObejctMapper productVersionObejctMapper;

    /**
     * 修改页面
     *
     * @param page 页面
     * @return 结果
     */
    @Override
    public int updatePage(Page page) {
        page.setUpdateTime(DateUtils.getNowDate());
        page.setUpdateBy(ShiroUtils.getLoginName());
        if (page.getParentId() != null) {
            Page page1 = this.selectPageById(page.getParentId());
            if (page1 == null) {
                page.setPageLevel("1");
            } else {
                page.setPageLevel((Integer.parseInt(page1.getPageLevel()) + 1) + "");
                page.setCategoryId(page1.getCategoryId());
            }
        }
        this.productVersionObejctMapper.removeByObjectId(page.getId(), "2");
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectId(page.getId());
        interfaceObject.setObjectType("2");
        List<InterfaceObject> interfaceObjectList = this.interfaceObjectMapper.selectInterfaceObjectList(interfaceObject);
        Map<Long, List<InterfaceObject>> collect = null;
        if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
            collect = interfaceObjectList.stream().collect(Collectors.groupingBy(InterfaceObject::getInterfaceId));
        }
        this.interfaceObjectMapper.removeByObject(Arrays.asList(page.getId()), "2");
        insertInterfaceObject(page.getId(), page.getInterfaceIds(), collect);
        if (page.getCategoryId() != null) {
            Category category = this.categoryMapper.selectCategoryById(page.getCategoryId());
            page.setCategoryCode(category.getCode());
        }

        if (CollectionUtil.isNotEmpty(page.getProductIds())) {
            List<ProductVersionObejct> list = new ArrayList<>();
            for (Long productId : page.getProductIds()) {
                if(productId ==null || productId == 0) continue;
                ProductVersionObejct object = new ProductVersionObejct();
                object.setObjectId(page.getId());
                object.setTableProductVersionId(productId);
                object.setObjectType("2");
                list.add(object);
            }
            if (list.size() > 0) {
                this.productVersionObejctMapper.batchSave(list);
            }
        }

        return pageMapper.updatePage(page);
    }

    @Resource
    private InterfaceObjectMapper interfaceObjectMapper;

    private void insertInterfaceObject(Long id, List<Long> interfaceIds, Map<Long, List<InterfaceObject>> collect) {
        if (CollectionUtil.isNotEmpty(interfaceIds)) {
            List<InterfaceObject> interfaceObjectList = new ArrayList<>();
            for (Long interfaceId : interfaceIds) {
                InterfaceObject interfaceObject = new InterfaceObject();
                interfaceObject.setObjectId(id);
                interfaceObject.setInterfaceId(interfaceId);
                interfaceObject.setObjectType("2");
                interfaceObject.setSortNum(0);
                if (collect != null) {
                    List<InterfaceObject> interfaceObjectList1 = collect.get(interfaceId);
                    if (CollectionUtil.isNotEmpty(interfaceObjectList1)) {
                        interfaceObject.setSortNum(interfaceObjectList1.get(0).getSortNum());
                    }
                }
                interfaceObjectList.add(interfaceObject);
            }
            this.interfaceObjectMapper.batchSave(interfaceObjectList);
        }
    }

    /**
     * 批量删除页面
     *
     * @param ids 需要删除的页面主键
     * @return 结果
     */
    @Override
    public int deletePageByIds(String ids) {
        return pageMapper.deletePageByIds(Convert.toStrArray(ids));
    }

    @Resource
    private UserDataAuthMapper userDataAuthMapper;

    /**
     * 删除页面信息
     *
     * @param id 页面主键
     * @return 结果
     */
    @Override
    public int deletePageById(Long id) {
        this.interfaceObjectMapper.removeByObject(Arrays.asList(id), "2");
        userDataAuthMapper.removeByObjectId(Arrays.asList(id), "3");
        FileInf fileInf = new FileInf();
        fileInf.setObjectId(id);
        fileInf.setObjectType("2");
        fileInf.setIsMaster(null);
        fileInf.setImgType(null);
        List<FileInf> fileInfs = this.fileInfoMapper.selectFileInfoList(fileInf);
        if (CollectionUtil.isNotEmpty(fileInfs)) {
            this.fileInfoMapper.deleteFileInfoObjectIdAndObjectType(id, "2");
            for (FileInf inf : fileInfs) {
                this.fileInfoMapper.deleteFileInfoByParentId(inf.getId());
            }
        }
        return pageMapper.deletePageById(id);
    }

    /**
     * 查询页面树列表
     *
     * @return 所有页面信息
     */
    @Override
    public List<Ztree> selectPageTree() {
        List<Page> pageList = pageMapper.selectPageList(new Page());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Page page : pageList) {
            Ztree ztree = new Ztree();
            ztree.setId(page.getId());
            ztree.setpId(page.getParentId());
            ztree.setName(page.getPageName());
            ztree.setTitle(page.getPageName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    @Override
    public List<Page> pageListByInterfaceId(List<Long> interfaceIds) {
        return this.pageMapper.pageListByInterfaceId(interfaceIds);
    }

    @Override
    public List<FileInf> selectPageFileByInterfaceId(Long interfaceId) {
        return this.pageMapper.selectPageFileByInterfaceId(interfaceId);
    }

    @Override
    public void addImg(Page page) {
        if (CollectionUtil.isNotEmpty(page.getFileInfList())) {
            for (FileInf fileInf : page.getFileInfList()) {
                fileInf.setObjectType("2");
                fileInf.setImgType(page.getImgType());
                fileInf.setObjectId(page.getId());
            }
            this.fileInfoMapper.batchSave(page.getFileInfList());
        }
    }

    @Override
    public List<Long> tableList(List<Long> interfaceIds) {
        return this.pageMapper.tableList(interfaceIds);
    }

    @Override
    public List<Page> selectPageListV2(Page page) {
        return list1(page);
    }

    private List<Page> list1(Page page) {
        List<Page> list = pageMapper.selectPageListV2(page);
        if (null == list || list.size() == 0) {
            return null;
        }
        // 循环查询出用户角色
        list.parallelStream().forEachOrdered(a -> {
            a.setHandlePower(false);
            UserDataAuth userDataAuth = new UserDataAuth();
            userDataAuth.setObjectId(a.getId());
            userDataAuth.setObjectType("3");
            List<UserDataAuth> userList = userDataAuthMapper.selectUserDataAuthListV2(userDataAuth);
            if (null != userList && userList.size() > 0) {
                List<UserDataAuth> filterList = userList.stream()
                        .filter(b -> b.getUserId().longValue() == ShiroUtils.getUserId())
                        .collect(Collectors.toList());
                if (null != filterList && filterList.size() > 0) {
                    a.setHandlePower(true);
                    a.setObjectStatus(filterList.get(0).getObjectStatus());
                }
                a.setUserList(userList);
            }
//            InterfaceObject interfaceObject = new InterfaceObject();
//            interfaceObject.setObjectType("2");
//            interfaceObject.setObjectId(a.getId());
//            List<InterfaceObject> result = interfaceObjectMapper.selectInterfaceObjectList(interfaceObject);
//            if (CollectionUtil.isEmpty(result)) {
//                return;
//            }
//            InterfaceInfo interfaceInfo = new InterfaceInfo();
//            interfaceInfo.setIds(result.stream().map(InterfaceObject::getInterfaceId).collect(Collectors.toList()));
//            List<InterfaceInfo> interfaceInfoList = interfaceInfoMapper.selectInterfaceInfoList2(interfaceInfo);
//            if (CollectionUtil.isEmpty(interfaceInfoList)) {
//                return;
//            }
            List<InterfaceInfo> interfaceInfoList = interfaceInfoMapper.selectInterfaceInfoList3(Collections.singletonList(a.getId()));
            a.setInterfaceList(interfaceInfoList);
        });
        return list;
    }

    private List<Page> list2(Page page) {
        List<Page> list = pageMapper.selectPageListV2(page);
        if (null == list || list.size() == 0) {
            return null;
        }
        List<Long> pageIds = list.stream().map(Page::getId).collect(Collectors.toList());
        UserDataAuth userDataAuth = new UserDataAuth();
        userDataAuth.setObjectIds(pageIds);
        userDataAuth.setObjectType("3");
        List<UserDataAuth> userList = userDataAuthMapper.selectUserDataAuthListV2(userDataAuth);
        Map<Long, List<UserDataAuth>> map = userList.stream().collect(Collectors.groupingBy(UserDataAuth::getObjectId));
        List<InterfaceInfo> interfaceInfoList = interfaceInfoMapper.selectInterfaceInfoList3(pageIds);
        Map<Long, List<InterfaceInfo>> interfaceMap = interfaceInfoList.stream().collect(Collectors.groupingBy(InterfaceInfo::getPageId));
        // 循环查询出用户角色
        list.parallelStream().forEachOrdered(a -> {
            a.setHandlePower(false);
            List<UserDataAuth> userList2 = map.get(a.getId());
            if (null != userList2 && userList2.size() > 0) {
                List<UserDataAuth> filterList = userList2.stream()
                        .filter(b -> b.getUserId().longValue() == ShiroUtils.getUserId())
                        .collect(Collectors.toList());
                if (null != filterList && filterList.size() > 0) {
                    a.setHandlePower(true);
                    a.setObjectStatus(filterList.get(0).getObjectStatus());
                }
                a.setUserList(userList2);
            }

            List<InterfaceInfo> interfaceInfoList2 = interfaceMap.get(a.getId());
            if (CollectionUtil.isEmpty(interfaceInfoList2)) {
                return;
            }
            a.setInterfaceList(interfaceInfoList2);
        });
        return list;
    }

    @Override
    public List<CategoryPageDto> queryPageAndInterface(Long categoryId) {
        return this.pageMapper.queryPageAndInterface(categoryId);
    }

    @Override
    public void updatePageInterfaceSort(List<PageInterfaceDto> pageInterfaceDtoList) {
        this.interfaceObjectMapper.updatePageInterfaceSort(pageInterfaceDtoList);
    }

    @Override
    public List<InterfaceInfo> queryInterfaceByPageId(Long pageId) {
        List<InterfaceInfo> interfaceInfoList = interfaceInfoMapper.selectInterfaceInfoList3(Collections.singletonList(pageId));
        return interfaceInfoList;
    }
}
